<?php
/**
 * @author by bilee.
 * 时间: 16/6/28 下午2:37
 * 公共函数
 */

/**
 * 验证用户token
 */
function verificationToken()
{
    $token = I("token");
    $uid = I("uid");
    if (!$token || !$uid) {
        exit(RET_NO_V(401, "token或者uid未填写"));
    }
    $app_users = M('app_users');
    $ret = $app_users->where(array('token' => $token, 'user_id' => $uid))->field('token,user_id')->find();
    if (!$ret) {
        exit(RET_NO_V(403, "非法请求！"));
    }
}

/**
 * 验证跑客用户token
 */
function pnerificationToken()
{
    $token = I("token");
    $uid = I("uid");
    if (!$token || !$uid) {
        exit(RET_NO_V(401, "token或者uid未填写"));
    }
    $dispatch = M('dispatch');
    $ret = $dispatch->where(array('token' => $token, 'dispatch_id' => $uid))->field('token,dispatch_id')->find();
    if (!$ret) {
        exit(RET_NO_V(403, "非法请求！"));
    }
}

/**
 * 验证管理用户token
 */
function managerificationToken()
{
    $token = I("token");
    $uid = I("uid");
    if (!$token || !$uid) {
        exit(RET_NO_V(401, "token或者uid未填写"));
    }
    $app_manager = M('app_manager');
    $ret = $app_manager->where(array('token' => $token, 'id' => $uid))->field('token,id')->find();
    if (!$ret) {
        exit(RET_NO_V(403, "非法请求！"));
    }
}

/**
 * 验证pc端用户token
 */
function verificationPcToken()
{
    $userinfo = $_SESSION['userinfo'];
    $user_id = $userinfo['user_id'];
    $token = $userinfo['token'];
    if(!isset($userinfo) || !isset($user_id) || !isset($token)){
        exit(RET_NO_V(403, "没有登录！"));
    }
    
}

/**
 * 创建订单函数001
 */
function createOrderId()
{
    return "BN" . date('Ymdhis', time()) . rand(000000, 999999);
}

/**
 * @desc 根据两点间的经纬度计算距离
 * @param float $lat 纬度值
 * @param float $lng 经度值
 *
 * @return @miles 英里
 *
 */
function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2)
{
    $theta = $longitude1 - $longitude2;
    $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
    $miles = acos($miles);
    $miles = rad2deg($miles);
    $miles = $miles * 60 * 1.1515;
    $feet = $miles * 5280;
    $yards = $feet / 3;
    $kilometers = $miles * 1.609344;
    $meters = $kilometers * 1000;
    return compact('miles', 'feet', 'yards', 'kilometers', 'meters');
}

/**
 * @desc 根据两点间的经纬度计算距离
 * @param float $lat 纬度值
 * @param float $lng 经度值
 */
function getDistance($lat1, $lng1, $lat2, $lng2)
{
    //dump($lat1."/".$lng1."/".$lat2."/".$lng2);
    //将角度转为弧度
    $radLat1 = deg2rad($lat1);
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;//两纬度之差,纬度<90
    $b = $radLng1 - $radLng2;//两经度之差纬度<180
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;
    return $s;
}


/**
 * 百度路线距离API
 * @$start 出发点经纬度
 * @$end 结束点经纬度
 */
function line($start, $end)
{
    $starts = explode(',', $start);
    $ends = explode(',', $end);
    $startlng = $starts[1];
    $startlat = $starts[0];
    $endlng = $ends[1];
    $endlat = $ends[0];

    //百度地图坐标转换为百度魔卡托坐标
    $bdmc = 'http://api.map.baidu.com/geoconv/v1/?coords=' . $startlng . ',' . $startlat . ';' . $endlng . ',' . $endlat . '&ak=oZduCbhCfT0SVjLqjfGB8TPe4edy14MG&from=3&to=6';
    //dump($bdmc);
    $ch = curl_init($bdmc);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $cexeCute = curl_exec($ch);
    curl_close($ch);
    $result = json_decode($cexeCute, true);
    //dump($result);
    $requestUrl = "http://api.map.baidu.com/routematrix/v2/riding?origins=" . $result['result'][0]['y'] . "," . $result['result'][0]['x'] . "&destinations=" . $result['result'][1]['y'] . "," . $result['result'][1]['x'] . "&ak=oZduCbhCfT0SVjLqjfGB8TPe4edy14MG&output=json&coord_type=bd09mc&tactics=12";
    //dump($requestUrl);
    $ch = curl_init($requestUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $cexeCute = curl_exec($ch);
    curl_close($ch);
    $results = json_decode($cexeCute, true);
    return $results;
}

/**
 * uu跑腿路径距离接口
 */
function line_uu($start, $end)
{
    $starts = explode(',', $start);
    $ends = explode(',', $end);
    $startlng = $starts[0];
    $startlat = $starts[1];
    $endlng = $ends[0];
    $endlat = $ends[1];
    $uu = 'http://wechat.uupaotui.com/NewOrder/BaduMethod.ashx?action=1002&start=' . $startlng . ',' . $startlat . '&end=' . $endlng . ',' . $endlat . '&mode=walking';
    $ch = curl_init($uu);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $cexeCute = curl_exec($ch);
    curl_close($ch);
    return json_decode($cexeCute, true);
}

/**
 * 跑客端未完成订单验证
 * @$status 当前订单状态
 * @$order_id 订单id
 */
function validationOrder($status, $order_id, $dispatch_id)
{
    $order_db = M('order');
    $ret = $order_db->where(array('dispatch_id' => $dispatch_id, 'status' => $status, 'order_id' => $order_id))->field('order_id,order_type,user_id,order_number')->find();
    return $ret;
}

/**
 * 订单支付状态字典
 * @$pay_status 订单支付状态 0，未支付，1、已支付，2、已退款
 */
function order_pay_status($status)
{
    switch ($status) {
        case 0:
            return "未支付";
            break;
        case 1:
            return "已支付";
            break;
        case 2:
            return "已退款";
            break;
    }
}

/**
 * 订单状态字典
 * @$status 状态  0、未分配，1、已分配，2、已取件，3、已送达，4、已完成，9，已取消。
 */
function order_status($status)
{
    switch ($status) {
        case 0:
            return "未分配";
            break;
        case 1:
            return "已分配";
            break;
        case 2:
            return "已取件";
            break;
        case 3:
            return "已送达";
            break;
        case 4:
            return "已完成";
            break;
        case 9:
            return "已取消";
            break;
    }
}

/**
 * 订单状态字典
 * @$status 状态 是否审核通过(0 未提交审核 1已提交审核，2已经审核通过 3审核未通过)
 */
function is_audit_status($status)
{
    switch ($status) {
        case 0:
            return "未提交审核";
            break;
        case 1:
            return "已提交审核";
            break;
        case 2:
            return "已经审核通过";
            break;
        case 3:
            return "审核未通过";
            break;
    }
}

/**
 * 上传照片
 * @param $rootPath 根目录地址
 */
function upImg($savePath)
{
    $saveName = date('YmdHis') . rand(0000000000, 9999999999);
    $config = array(
        'maxSize' => 3145728,
        'rootPath' => './Uploads/',
        'savePath' => $savePath,
        'saveName' => $saveName,
        'exts' => array('jpg', 'gif', 'png', 'jpeg'),
        'autoSub' => true,
        'subName' => '',

    );
    $upload = new \Think\Upload($config);// 实例化上传类
    // 上传文件
    $info = $upload->upload();
    //return $info;
    if (!$info) {// 上传错误提示错误信息
        return array('retCode' => 400, 'retDesc' => $upload->getError());
    } else {// 上传成功
        $date = date('Ymd');
        $filePath = 'Uploads' . $savePath . $info['photo']['savename'];
        return array('retCode' => 200, 'retDesc' => $filePath);
    }
}


/**
 * 上传录音方法
 * @param $rootPath 根目录地址
 */
function up_amr($savePath)
{
    $saveName = date('YmdHis') . rand(0000000000, 9999999999);
    $config = array(
        'maxSize' => 3145728,
        'rootPath' => './Uploads/',
        'savePath' => $savePath,
        'saveName' => $saveName,
        'exts' => array('amr'),
        'autoSub' => true,
        'subName' => '',

    );
    $upload = new \Think\Upload($config);// 实例化上传类
    // 上传文件
    $info = $upload->upload();
    //return $info;
    if (!$info) {// 上传错误提示错误信息
        return array('retCode' => 400, 'retDesc' => $upload->getError());
    } else {// 上传成功
        $date = date('Ymd');
        $filePath = 'Uploads' . $savePath . $info['amr']['savename'];
        return array('retCode' => 200, 'retDesc' => $filePath);
    }
}

/**
 * 封装用户资金记录的方法
 * @user_id int 用户ID
 * @purse_type int 类型:1、充值，2、消费，3、退款，4、代收货款结算，5、提款
 * @purse_amount int 变动金额 10
 * @change_remark string 变动说明(活动说明之类)
 * @recharge_record_id int 充值记录id
 * @order_id int 订单ID
 * @user_set_id int 代收款id
 * @cash_record_id int 提款记录id
 */
function userPurseLog($user_id, $purse_type, $purse_amount, $change_remark, $recharge_record_id, $order_id, $user_set_id = NULL, $cash_record_id = NULL)
{
    $user_purse = M('user_purse');
    $data = array(
        'user_id' => $user_id,
        'purse_type' => $purse_type,
        'purse_amount' => $purse_amount,
        'change_time' => date('Y-m-d H:i:s', time()),
        'change_remark' => $change_remark,
        'recharge_record_id' => $recharge_record_id,
        'order_id' => $order_id,
        'user_set_id' => $user_set_id,
        'cash_record_id' => $cash_record_id,
        'sum_amount'=>get_user_balance($user_id)+$purse_amount
    );
    return $user_purse->add($data);
}


/**
 * 封装跑客资金记录的方法
 */
function dispatchPurseLog($dispatch_id, $balance_type, $balance_amount, $change_memo, $remark, $order_id, $user_set_id = NULL, $coin_id = NULL)
{
    $dispatch_balance = M('dispatch_balance');
    $data = array(
        'dispatch_id' => $dispatch_id,
        'balance_type' => $balance_type,
        'balance_amount' => $balance_amount,
        'time' => date('Y-m-d H:i:s', time()),
        'change_memo' => $change_memo,
        'remark' => $remark,
        'order_id' => $order_id,
        'cash_record_id' => $user_set_id,
        'coin_id' => $coin_id,
        'sum_amount'=>get_dispatch_balance($dispatch_id)+$balance_amount
    );
    return $dispatch_balance->add($data);
}

/**
 * 根据用户ID获取用户昵称
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getUserName($uid)
{
    $app_users = M("app_users");
    $ret = $app_users->where(array('user_id' => $uid))->field('user_name')->find();
    return $ret['user_name'];
}

/**
 * 根据用户ID获取跑客姓名
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getDispatchName($uid)
{
    $app_users = M("dispatch");
    $ret = $app_users->where(array('dispatch_id' => $uid))->field('dispatch_name')->find();
    return $ret['dispatch_name'];
}

/**
 * 作用：将xml转为array
 */
function xmlToArray($xml)
{
    //将XML转为array
    $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $array_data;
}

/**
 * 取消订单时记录取消情况
 * @param $order_id 订单id
 * @param $user_id 用户id
 * @param $dispatch_id 跑客id
 * @param $cancle_party 取消方，1用户2跑客
 * @param $remark 备注
 * @return int 0取消失败，1取消成功，2参数不合法
 */
function addOrderCancle($order_id, $user_id, $dispatch_id, $status, $cancle_party, $remark)
{
    if (!$order_id || !$user_id || !$cancle_party)
        return 2;
    $data = array('order_id' => $order_id
    , 'user_id' => $user_id
    , 'dispatch_id' => $dispatch_id
    , 'cancle_party' => $cancle_party
    , 'order_status' => $status
    , 'remark' => $remark
    , 'cancle_time' => date('Y-m-d H:i:s', time())
    );
//    dump('取消信息：');
//    dump($data);
    $order_cancle_db = M('order_cancle');
    $add_ret = $order_cancle_db->add($data);

    if ($add_ret) {
        return 1;
    } else {
        return 0;
    }


}

/**
 * 在登录或由后台转前台时，将新的公告信息，写入message_sys表中
 * @param $uid 用户id
 * @param $utype 用户类别
 * @return false：参数或操作有误，true：成功
 */
function login_upmsg_sys($uid, $utype)
{
    $message_sys_db = M('message_sys');
    $message_db = M('message');
    $send_time = date('Y-m-d H:i;s', time());
    $msg_sys_obj = $message_sys_db->where(array('uid' => $uid, 'message_type' => $utype))->find();
//    dump('跑客系统信息表是否存在该用户：');
//    dump($message_sys_db->getLastSql());
//    dump($msg_sys_obj);
    $up_ret = 1;
    if ($msg_sys_obj) {//用户系统消息修改
        $where = 1;
        if ($msg_sys_obj['login_update_time'])
            $where .= " and send_time >= '" . $msg_sys_obj['login_update_time'] . "'";
        $where .= " and message_type = " . $utype;

        $msg_objs = $message_db->field('GROUP_CONCAT(message_id) as msg_ids,count(message_id) as counts')->where($where)->find();//查询公告表
//        dump('公告表集合：');
//        dump($message_db->getLastSql());
//        dump($msg_objs);

        if ($msg_objs && $msg_objs['msg_ids']) {
            if ($msg_sys_obj['unread_msgids']) {
                $data['unread_msgids'] = $msg_sys_obj['unread_msgids'] . ',' . $msg_objs['msg_ids'];
                $data['unread_counts'] = $msg_sys_obj['unread_counts'] + $msg_objs['counts'];
            } else {
                $data['unread_msgids'] = $msg_objs['msg_ids'];
                $data['unread_counts'] = $msg_objs['counts'];
            }

            $data['login_update_time'] = date('Y-m-d H:i;s', time());
//            dump('修改数据');
//            dump($data);
            $up_ret = $message_sys_db->where(array('sysmsg_id' => $msg_sys_obj['sysmsg_id']))->save($data);
            if ($up_ret) {
                return true;
            } else
                return false;
        } else
            return true;
    } else {//用户系统消息新增
        $msg_objs = $message_db->field('GROUP_CONCAT(message_id) as msg_ids,count(message_id) as counts')->where("send_time <= '" . $send_time . "' and message_type = " . $utype)->find();//查询公告表
        if ($msg_objs) {
            $data['unread_msgids'] = $msg_objs['msg_ids'];
            $data['unread_counts'] = $msg_objs['counts'];
            $data['read_counts'] = 0;
            $data['login_update_time'] = date('Y-m-d H:i;s', time());
            $data['uid'] = $uid;
            $data['message_type'] = $utype;

            $add_ret = $message_sys_db->add($data);
            if ($add_ret) {
                return true;
            } else
                return false;
        }
    }
}

/**
 * 查看系统消息，将已查看的记录写入message_sys表已读字段中
 * @param $uid 用户id
 * @param $message_id 消息id
 * @return false：参数或操作有误，true：成功
 */
function see_upmsg_sys($uid, $message_id)
{
    $message_sys_db = M('message_sys');
    $message_db = M('message');
    $msg_obj = $message_db->field('message_id,message_type')->where(array('message_id' => $message_id))->find();//查询公告表
//    dump('系统消息：');
//    dump($message_db->getLastSql());
//    dump($msg_obj);

    if ($msg_obj) {
        $sys_obj = $message_sys_db->where(array('uid' => $uid, 'message_type' => $msg_obj['message_type']))->find();
//        dump('系统消息：');
//        dump($sys_obj);
        $unread_msgids = $sys_obj['unread_msgids'];
//        dump('未读串：');
//        dump($unread_msgids);
//        dump('查找id：');
//        dump($message_id);
        $unread_arr = explode(",", $unread_msgids);
        $search_ret = array_search($message_id, $unread_arr);

//        $pos = strpos($unread_msgids,$message_id);
//        dump('查找结果：');
//        dump($search_ret);

        if ($search_ret === false) {
            return true;
        } else {
            unset($unread_arr[$search_ret]);
//            dump($unread_arr);

            $new_unread_str = implode(',', $unread_arr);;
//            dump($new_unread_str);

            if ($sys_obj['read_msgids']) {
                $data['read_msgids'] = $sys_obj['read_msgids'] . ',' . $message_id;
                $data['read_counts'] = $sys_obj['read_counts'] + 1;
            } else {
                $data['read_msgids'] = $message_id;
                $data['read_counts'] = 1;
            }
            $data['unread_msgids'] = $new_unread_str;
            $data['unread_counts'] = $sys_obj['unread_counts'] - 1;
            $data['read_update_time'] = date('Y-m-d H:i;s', time());
//            dump('修改前数据');
//            dump($data);

            $save_ret = $message_sys_db->where('sysmsg_id=' . $sys_obj['sysmsg_id'])->save($data);
            if ($save_ret) {
                return true;
            } else
                return false;
        }
    } else {
        return false;
    }
}

/**
 * 系统消息列表，返回哪些已读，哪些未读
 * @param $uid 用户id
 * @param $message_type 消息类别 1：用户消息，2：跑客消息
 * @param $page 开始页数
 * @param $pagenum 每页显示的记录数
 * @return 消息公告集合，或 null
 */
function upmsg_sys_list($uid, $message_type, $page = 1, $pagenum = 7)
{
    $message_sys_db = M('message_sys');
    $message_db = M('message');
    $sys_obj = $message_sys_db->where(array('uid' => $uid, 'message_type' => $message_type))->find();

    if ($sys_obj) {
        $unread_msgids = $sys_obj['unread_msgids'];
        $msg_objs = $message_db->where('message_type=' . $message_type)->order('send_time desc')->limit(($page - 1) * $pagenum, $pagenum)->select();//查询公告表
        $count = $message_db->where('message_type=' . $message_type)->count();

        if ($msg_objs) {
            foreach ($msg_objs as $key => $value) {
                $message_id = $value['message_id'];
                $unread_arr = explode(",", $unread_msgids);
                $search_ret = array_search($message_id, $unread_arr);
                if ($search_ret === false) {
                    $msg_objs[$key]['is_read'] = 1;
                } else {
                    $msg_objs[$key]['is_read'] = 0;
                }
            }
            $rets['data'] = $msg_objs;
            $rets['count'] = ceil($count / $pagenum);
            return $rets;
        } else
            return null;
    } else {
        return null;
    }
}

/**
 * 获取系统消息未读记录数
 * @param $uid 用户id
 * @return int 未读记录数
 */
function  getmsg_sys_unread($uid, $message_type)
{
    $message_sys_db = M('message_sys');
    $sys_obj = $message_sys_db->where(array('uid' => $uid, 'message_type' => $message_type))->find();

    $count = 0;
    if ($sys_obj) {
        $count = $sys_obj['unread_counts'];
    }
    return $count;
}

/**
 * @param $city_id 城市ID
 */
function city_name($city_id)
{
    $location = M('location');
    return $location->where(array('id' => $city_id))->field('city,id')->find();
}

/**
 *
 */
function team_name($company_id)
{
    $company = M('company');
    $ret = $company->where(array('company_id' => $company_id))->field('company_name')->find();
    return $ret['company_name'];
}

/**
 * 计算app在后台的时间
 */
function count_background_time($dispatch_id)
{

    $dispatch_db = M('dispatch');
    $dispatch_obj = $dispatch_db->field('todaytime,onlinetime')->where(array('dispatch_id' => $dispatch_id))->find();
    if (!$dispatch_obj)
        return false;
//    dump($dispatch_obj);
    $dis_active_db = M('dispatch_active');
    $dis_active_obj = $dis_active_db->where(array('dispatch_id' => $dispatch_id))->find();
    if (!$dis_active_obj)
        return true;

    $background_time = strtotime($dis_active_obj['time']);//进入后台的时间
    $now_time = time();//当前时间

    $background_date = date('Y-m-d', $background_time);//进入后台的日期
    $today_date = date('Y-m-d', $now_time);//当前的日期
    $yestoday_date = date("Y-m-d", strtotime("-1 day"));//昨天的日期
//    dump('后台日期：'.$background_date);
//    dump('今天日期：'.$today_date);
//    dump('昨天日期：'.$yestoday_date);

    if ($background_date == $today_date) {//是今天
        $total_minute = round(($now_time - $background_time) / 60);//当前时间距离进入后台的分钟数
        if ($total_minute == 0)
            return true;
        $totay = $total_minute;
    } elseif ($background_date == $yestoday_date) {//是昨天
        $totay = round(($now_time - strtotime($today_date . ' 00:00:00')) / 60);//当前时间-凌晨  的分钟数
        $total_minute = round(($now_time - $background_time) / 60);//当前时间-后台时间 的分钟数
//        $total_minute = $totay + $yestoday; //昨天 +　今天　　的在线分钟数
    } else //其他时间
        return true;

    $up_ret = $dispatch_db->where(array('dispatch_id' => $dispatch_id))
        ->setField(array('todaytime' => $dispatch_obj['todaytime'] + $totay,
            'onlinetime' => $dispatch_obj['onlinetime'] + $total_minute));
    if ($up_ret)
        return true;
    else
        return false;

}

/**
 * 有预约单，是否可以接单
 * @param $dispatch_id 接单跑客id
 * @param $new_reser_time_start 新预约单的开始时间  时间戳
 * @param $new_reser_time_end 新预约单的结束时间  时间戳
 * @return bool
 */
function is_pnrob_reservation($dispatch_id, $new_reser_time_start, $new_reser_time_end)
{
    $order_db = M('order');
    $reservation_objs = $order_db->field('order_type,is_reservation,reservation_time,queue_time,hour_long')->where('dispatch_id=' . I('uid') . ' and status>1 and status<7 and is_reservation=1')
        ->order('order_time desc')
        ->select();//有已接的预约单,   17:00取送,15:00取送，12:00，排队半个小时
    if (!$reservation_objs)
        return true;

    //
    foreach ($reservation_objs as $key => $value) {
//        dump('已有预约单的类型：');
//        dump($value['order_type']);
        $start_time = 0;
        $end_time = 0;

        if ($value['order_type'] == 3) {
            $start_time = strtotime($value['queue_time']) - floatval(C('reser_order_sqace')) * 60 * 60;//预约单开始前2个小时才可以接单
            $end_time = $start_time + $value['hour_long'] * 60;//分钟 *６０
        } else {
            $start_time = strtotime($value['reservation_time']) - floatval(C('reser_order_sqace')) * 60 * 60;//预约单开始前2个小时才可以接单
//            dump($value['reservation_time']);
            $end_time = strtotime($value['reservation_time']) + C('noqueue_reserorder_finishtime') * 60 * 60;//3（小时）* 60 *６０//非排队预约单完成时间段3个小时后才可以接单
        }
//        dump(date('Y-m-d H:i:s',$start_time));
//        dump(date('Y-m-d H:i:s',$end_time));
        if (($new_reser_time_start >= $start_time && $new_reser_time_start < $end_time)
            || ($new_reser_time_end > $start_time && $new_reser_time_end <= $end_time)
        )
            return false;
    }
    return true;
}

/**
 * 测试方法：有预约单，是否可以接单
 * @param $reservation_objs 预约单数组
 * @param $new_reser_time_start 新预约单开始时间
 * @param $new_reser_time_end 新预约单结束时间
 * @return bool true：可以接单，false：不可以接单
 */
function test_pnrob_reservation($reservation_objs, $new_reser_time_start, $new_reser_time_end)
{
//	$order_db = M('order');
//	$reservation_objs = $order_db->field('order_type,is_reservation,reservation_time,queue_time,hour_long')->where('dispatch_id=' . I('uid') . ' and status>1 and status<7 and is_reservation=1')
//		->order('order_time desc')
//		->select();//有已接的预约单,   17:00取送,15:00取送，12:00，排队半个小时
    if (!$reservation_objs)
        return true;

//    dump($reservation_objs);
    //
//    dump(C('noqueue_reserorder_finishtime'));
//    dump(C('reser_order_sqace'));
    foreach ($reservation_objs as $key => $value) {
//        dump('已有预约单的类型：');
//        dump($value['order_type']);
        $start_time = 0;
        $end_time = 0;

        if ($value['order_type'] == 3) {
            $start_time = strtotime($value['queue_time']) - floatval(C('reser_order_sqace')) * 60 * 60;//预约单开始前2个小时才可以接单
            $end_time = $start_time + $value['hour_long'] * 60;//分钟 *６０
        } else {
            $start_time = strtotime($value['reservation_time']) - floatval(C('reser_order_sqace')) * 60 * 60;
//            dump($value['reservation_time']);

            $end_time = strtotime($value['reservation_time']) + C('noqueue_reserorder_finishtime') * 60 * 60;//3（小时）* 60 *６０//非排队预约单完成时间段3个小时后才可以接单

        }
//        dump(date('Y-m-d H:i:s',$start_time));
//        dump(date('Y-m-d H:i:s',$end_time));
        if (($new_reser_time_start >= $start_time && $new_reser_time_start < $end_time)
            || ($new_reser_time_end > $start_time && $new_reser_time_end <= $end_time)
        )
            return false;
    }
    return true;
}

/**
 * 订单完成时，给系统中没有的联系人发短信
 * @param $order_id
 */
function app_market_order_linkman($order_id)
{
    $order_obj = M('order')->field('reci_mobile,replace_mobile')->where('order_id=' . $order_id)->find();

    if ($order_obj) {
        $mobile = $order_obj['reci_mobile'];
        if ($order_obj['order_type'] == 3)
            $mobile = $order_obj['replace_mobile'];

        $app_user_obj = M('app_users')->where('mobile=' . $mobile)->find();
        if (!$app_user_obj)
            send_market_mobile($mobile,"SMS_36100197");
            return true;
    } else {
        return false;
    }
}

/**
 * 根据接单量奖励跑客金额  $insurance_type=10
 * @param $dispatch_id 跑客id 必填
 * @param $order_id 订单id 必填
 * @param $insurance_amount 保险金额 必填
 * @return int 0插入数据出错，1：奖励成功，2：参数有误，3不需要扣除
 */
function dispatch_insurance($dispatch_id, $order_id, $insurance_type, $titel = "")
{
    if (!$dispatch_id || !$order_id)//参数为空
        return 2;

    $order_db = M('order');
    $order_obj = $order_db->where(array('order_id' => $order_id, 'dispatch_id' => $dispatch_id))->find();

    if (!$order_obj)
        return 2;

    $counts = $order_db->where("dispatch_id = " . $dispatch_id . "  and DATE_FORMAT(order_time,'%Y-%m-%d') = DATE_FORMAT(now(),'%Y-%m-%d') and status > 5 and status !=9 ")->count();

    $insurance_amount = 0;

//    $dispatch_obj = M('dispatch')->field('company_id')->where('dispatch_id='.$dispatch_id)->find();

    $titel = '日单量' . $counts . '单';
    if ($counts == 1) {
        $insurance_amount = 2;//奖励金额
        $titel = '每日首单';
    }
//    elseif($counts == 4 && $dispatch_obj && $dispatch_obj['company_id'] == 3)
//        $insurance_amount = 40;//奖励金额
//    elseif ($counts > 4 and $counts < 10 && $dispatch_obj && $dispatch_obj['company_id'] == 3)
//        $insurance_amount = 10;//奖励金额

    if ($insurance_amount == 0)
        return 3;
    //新增钱包记录
    $ret_detail = pnOrderDetail($dispatch_id, $insurance_amount, $insurance_type, $titel . '，奖励' . $insurance_amount . '元', $order_id, $titel . '，奖励' . $insurance_amount . '元');

    if (!$ret_detail)//钱包余额插入失败
        return 0;
    $ret = update_user_dispatch_blance($dispatch_id, 2, $insurance_amount); //修改余额
    //发消息
    if ($ret == 1) {
        $msg_ret = create_dispatch_message($dispatch_id, $titel . '奖励', $titel . '，奖励' . $insurance_amount . '元', $titel . '，奖励' . $insurance_amount . '元');
        return $msg_ret;
    } else
        return $ret;

}

//===========================================================
/**
 * PC_短信验证码获取及记录  $insurance_type=10
 * @param $phone_number 手机号 必填
 */
function pc_get_sms($phone_number)
{
    if (empty($phone_number)) {
        return false;
    }
    //实例化类
    $client = new \Alidayu\AlidayuClient();
    $request = new \Alidayu\Request\SmsNumSend();
    //生成随机验证码
    $chars = str_repeat('0123456789', 4);
    $chars = str_shuffle($chars);
    $code = substr($chars, 0, 4);
    //短信内容参数
    $smsParams = array(
        'code' => $code,
        'product' => '帮你跑腿'
    );
    // 设置请求参数
    $req = $request->setSmsTemplateCode('SMS_12831629')
        ->setRecNum($phone_number)
        ->setSmsParam(json_encode($smsParams))
        ->setSmsFreeSignName('帮你跑腿')
        ->setSmsType('normal')
        ->setExtend('demo');
    $status = $client->execute($req);
    if ($status["alibaba_aliqin_fc_sms_num_send_response"]["result"]["success"]) {
        $sms_log = M("sms_log");
        $ret = $sms_log->add(array(
            'sms_code' => $code,
            'sms_send_phone' => $phone_number,
            'sms_time' => date('Y-m-d H:i:s',time()),
            'sms_ip' => get_client_ip()
        ));
        return true;
    } else {
        return false;
    }
}


/**
 * 根据跑客iD返回跑客姓名
 * @param $dispatch_id 跑客ID必填
 */
function get_dispatch_name($dispatch_id)
{
    $dispatch = M("dispatch");
    $dispatch_name = $dispatch->where(array('dispatch_id'=>$dispatch_id))->field('dispatch_name')->find();
    return $dispatch_name['dispatch_name'];
}

/**
 * 根据跑客iD返回跑客手机号
 * @param $dispatch_id 跑客ID必填
 */
function get_dispatch_tel($dispatch_id)
{
    $dispatch = M("dispatch");
    $dispatch_name = $dispatch->where(array('dispatch_id'=>$dispatch_id))->field('mobile')->find();
    return $dispatch_name['mobile'];
}
/**
 * 根据用户iD返回用户手机号
 * @param $dispatch_id 跑客ID必填
 */
function get_user_tel($user_id)
{
    $user_db = M("app_users");
    $mobile = $user_db->where(array('user_id'=>$user_id))->getField('mobile');
    return $mobile;
}
/**
 * 关于中奖概率算法
 * 函数getRand()会根据数组中设置的几率计算出符合条件的id，我们可以接着调用getRand()。
 * @param $proArr
 * @return int|string
 */
function getRand($proArr) {
    $result = '';

    //概率数组的总概率精度
    $proSum = array_sum($proArr); //返回数组中所有值的和

    //概率数组循环
    foreach ($proArr as $key => $proCur) {
        //mt_rand：使用 Mersenne Twister 算法返回随机整数。语法：mt_rand(min,max)，该函数用了 Mersenne Twister 中已知的特性作为随机数发生器，它可以产生随机数值的平均速度比 libc 提供的 rand() 快四倍。
        $randNum = mt_rand(1, $proSum);//获得1到$proSum间的随机数，包括1和$proSum
        if ($randNum <= $proCur) {
            $result = $key;
            break;
        } else {
            $proSum -= $proCur;//和值-数组的值
        }
    }
    unset ($proArr);
//    dump('中奖概率结果：');
//    dump($result);
    return $result;
}

/**
 * 获得一个角度，返回
 *
 */
function getAngle($prize_arr){
//    dump('奖项数组：');
//    dump($prize_arr);
    foreach ($prize_arr as $key => $val) {
        $arr[$val['id']] = $val['v'];
    }
//    dump('奖项概率数组：');
//    dump($arr);
    $rid = getRand($arr); //根据概率获取奖项id
//    dump('中奖概率结果：');
//    dump($rid);
    $res = $prize_arr[$rid-1]; //中奖项
    $min = $res['min'];
    $max = $res['max'];
//    dump('中奖项：');
//    dump($res);
    if($res['id']==8){ //七等奖
        $i = mt_rand(0,5);
        $result['angle'] = mt_rand($min[$i],$max[$i]);
    }else{
        $result['angle'] = mt_rand($min,$max); //随机生成一个角度
    }
    $result['prize'] = $res['prize'];
//    dump('中奖结果：');
//    dump($result);
    return $result;
}

/**
 * 获得当月的战力值和魅力值
 * @param $dispatch_id
 */
function getThisMonthOrderCount($dispatch_id){
    if(!$dispatch_id)
        return array('order_amount'=>number_format(0,2),'user_eval_value'=>0);

    $order_db = M('order o ');
    $start_time = date('Y-m',time()).'-1 00:00:00';
    $end_time = date('Y-m-d',time()).' 23:59:59';

    $where = array('status'=>7,'dispatch_id'=>$dispatch_id,'o.finish_time'=>array('between',array($start_time,$end_time)));
    $ret = $order_db->field('ifnull(count(o.order_id),0) as order_count,ifnull(sum(o.user_eval_value),0) as user_eval_value')->where($where)->find();

    return $ret;

}

/**
 * 新用户下单，赠送推荐人优惠券或现金余额
 * @param $login_id
 * @return int
 */
function send_coupon($login_id){
    $recommend = M('recommend');
    //获取推荐人
    $recommend_status = $recommend->where(array('recommended_person_id' => $login_id, 'recommended_person_type' => 1))
                                 ->field('recommend_id,recommended_status,recom_person_id,recom_person_type,recommended_person_id')->find();
    if(!$recommend_status)//无推荐人
        return 2 ;
    $order_count = M('order')->where(array('user_id' => $login_id, 'status' => 7))->count();
//    dump("订单的数量");
//    dump($order_count);

    if($order_count >0 )//非第一单
        return 2;
//    dump($recommend_status);


    //=============新用户注册成功--随机奖励推荐人；用户1~3元优惠券，跑客1-2元余额============
    if ($recommend_status['recom_person_type'] == 1) {//推荐人是用户,被推荐人是用户的，给推荐人发优惠券，被推荐人是跑客的，不发优惠券
            $rand = rand(1, 2);

            if ($rand == 1)
                $rand_key = 'S7Rz6VbZHeNy7NrB';
            else if ($rand == 2)
                $rand_key = 'ecnnL%Oywj7#j6X!';
            //else if($rand == 3)
            //    $rand_key = '19^T6QsQneyES@w9';

            $rand_ret = newuser_reward_coupon2($recommend_status['recom_person_id'], $rand_key, $recommend_status['recommended_person_id']);//奖励推荐人优惠券
//        dump('是否能给优惠券');
//        dump($rand_ret);
            if (1 == $rand_ret) {
                //优惠券发放成功发消息
                $coupon_info = M("coupon_info");
                $cou_ret1 = $coupon_info->field('coupon_value')->where("coupon_key='" . $rand_key . "' and is_push=1 and surplus_num >=0")->find();
//                dump("优惠券信息：") ;
//                dump($cou_ret1) ;

                $user_msg_ret = create_user_message($recommend_status['recom_person_id'], '推荐新用户注册登录成功有礼', '随机奖励' . $rand . '元优惠券已发放给您', '随机奖励' . $rand . '元优惠券已发放给您');
                if($cou_ret1 && $user_msg_ret)
                    return 1;
                else
                    return 0;
            }else
                return 3;
        } elseif ($recommend_status['recom_person_type'] == 2) {//推荐人是跑客，奖励1-2元余额
            $dispatch_balance_db = M('dispatch_balance');
            $dis_balance = $dispatch_balance_db->where(array('dispatch_id'=>$recommend_status['recom_person_id'],'recommended_person_id'=>$recommend_status['recommended_person_id']))->field('recommended_person_id')->find();
//            dump('是否返钱：');
//            dump($dis_balance);
            if($dis_balance)
                return 2;
            $rand = rand(1, 2);
            //增加余额，增加推荐奖励金额
            $user_db = M('dispatch');
            $user_purse = $user_db->where(' dispatch_id = ' . $recommend_status['recom_person_id'])->field('cash_balance,recommend_amount')->find();
            $cash_balance = floatval($user_purse['cash_balance']) + $rand;//推荐人的账户金额
            $recommen_count = floatval($user_purse['recommend_amount']) + $rand;//推荐人的推荐金额

        //跑客钱包表
//            $balance_ret = create_dispatch_balance($recommend_status['recom_person_id'], 5, $rand, 0, '推荐新用户注册登录成功，随机奖励' . $rand . '元');
            $data = array(
                'balance_type' => 5,
                'dispatch_id' => $recommend_status['recom_person_id'],
                'balance_amount' => $rand,
                'time' => date('Y-m-d H-i-s', time()),
                'change_memo' => '推荐新用户注册登录成功，随机奖励' . $rand . '元',
                'recommended_person_id' => $login_id,
                'remark' => '推荐新用户注册登录成功，随机奖励' . $rand . '元',
                'sum_amount'=>$cash_balance
            );

            $balance_ret = $dispatch_balance_db->add($data);
//            dump("跑客信息：") ;
//            dump($user_purse) ;
//            dump("推荐人的账户金额：") ;
//            dump($cash_balance);
//            dump("推荐人的推荐金额：") ;
//            dump($cash_balance);

            $dispatch_ret = $user_db->where('dispatch_id=' . $recommend_status['recom_person_id'])->setField(array('recommend_amount' => $recommen_count, 'cash_balance' => $cash_balance));
        
            //发送推荐奖励消息
            $dismsg_ret = create_dispatch_message($recommend_status['recom_person_id'], '推荐新用户注册登录成功有礼', '随机奖励' . $rand . '元已存入您的账户', '随机奖励' . $rand . '元已存入您的账户');

            if($dispatch_ret && $balance_ret && $dismsg_ret)
                return 1;
            else
                return 0;
        }
    return 4;
}
/**
 * 把转盘中奖结果写入数据库
 * @param $angle
 * @return int
 */
//
 function  record_data($angle){
      $user_prize = M('user_prize');
      if($angle){
                $sql = "select coupon_id as prize_id,coupon_key as prize_key,effective_days from db_coupon_info where title like '%".$angle["prize"]."%'";
              //  dump($sql);
                $data = M()->query($sql);
              //  dump($data);
                $add_time = date("Y-m-d H:i:s", time());      
                $ret_data = $data[0];
                $ret_data['user_id'] = I('uid');
                $ret_data['prize_angle'] = $angle["angle"];
                $ret_data['prize_result'] = $angle["prize"];
                $ret_data['is_used'] = 1;
                $ret_data['add_time'] = $add_time;
                $ret_data['remark'] = "转盘抽奖";
                //把有效天数转为有效截止时间
                $ret_data['valid_end_time'] = strtotime($ret_data['add_time'])+(30*24*60*60); 
                //dump($ret_data['valid_end_time']);
                $ret_data['valid_end_time'] = date("Y-m-d",$ret_data['valid_end_time'])." 23:59:59";
                //dump($ret_data['valid_end_time']);
                $money = substr($angle["prize"],0,1);
//                    if(strpos($angle["prize"], '代金'))
//                    {
//                     //1、代金券，结果写入抽奖表
//                        $result = $user_prize->data($ret_data)->add();
//                        if(!$result){
//                           return RET_NO_V(0, "抽奖数据写入数据库失败！");
//                           }
//                     //1,代金券，写入用户钱包
//                        $user_purse = M('user_purse');
//                        $pur_data = array(
//                            'user_id' => I('uid'),
//                            'purse_amount' =>$money,
//                            'purse_type' => 7,
//                            'change_time' => $add_time,
//                            'change_remark'=> "转盘抽奖收入"
//                        );
//                        $pur_result = $user_purse->data($pur_data)->add();
//                        if(!$pur_result){
//                            return RET_NO_V(0, "抽奖数据写入用户钱包失败！");
//                        }
//                        $app_users = M('app_users');
//                        $purse_money = $app_users->where(array('user_id'=>I('uid')))->getField('purse_balance');
//                        $purse_money = $money + $purse_money;
//                        $data['purse_balance'] = $purse_money ;
//                        $user_ret = $app_users ->where(array('user_id'=>I('uid')))->save($data);
//
//                        if(!$user_ret){
//                            return RET_NO_V(0, "抽奖数据写入用户金额失败！");
//                        }
//                    }else 
                    if(strpos($angle["prize"], '优惠')){
                        //优惠券，结果写入抽奖表
                        $result = $user_prize->data($ret_data)->add();
                        if(!$result){
                            return 0;//RET_NO_V(0, "抽奖数据写入抽奖表失败！");
                        }
                       //2优惠券，结果写入用户优惠券表
                        $user_coupon = M('user_coupon');
                        $ret_cou = array(
                            'coupon_id' => $data[0]['prize_id'],
                            'user_id' => I('uid'),
                            'coupon_type' => 1,
                            'coupon_value' => $money,
                            'remark' => '转盘抽奖优惠',
                            'valid_end_time' => $ret_data['valid_end_time'],
                            'from_remark' => "APP兑换抵扣券，金额为".$money."元",
                            'is_used' => 1,
                            'coupon_key' => $data[0]['prize_key']
                        );
                        //dump($ret_cou);
                        $cou_result = $user_coupon->data($ret_cou)->add();
                        if(!$cou_result){
                            return 0; //RET_NO_V(0, "抽奖数据写入用户钱包失败！");
                        }
                    }else if(strpos($angle["prize"], '惠顾')){
                        $ret_data['prize_id'] = "";
                        $result = $user_prize->data($ret_data)->add();
                        if(!$result){
                            return  0;//RET_NO_V(0, "抽奖数据写入数据库失败！");
                        }
                    }else{
                     //3、实物，结果写入抽奖表
                        $ret_data['prize_id'] = "";
                        $result = $user_prize->data($ret_data)->add();
                        if(!$result){
                            return 0;//RET_NO_V(0, "抽奖数据写入数据库失败！");
                        }
                    }
            }else
                return  false;   //RET_NO_V(0, "获取角度失败！");
 }
 /**
 * 转盘抽奖减积分
 * @param $uid
 * @return int
 */
 //转盘抽奖减积分
 function integral_subtraction($uid){
     $app_users = M('app_users');
     $points_value = $app_users->where(array('user_id' => $uid))->getField('points_value');
//     echo $app_users->getLastSql();
     if($points_value < 100)
     {
         return false;
     }
     $points_value -= 100;
     $data = $app_users->where(array('user_id' => $uid))->save(array('points_value'=>$points_value));
//     dump($points_value );
//     dump($data);
     return $data;
 }
  /**
 * 积分兑换优惠券
 * @param $uid
 * @param $inte
 * @return int
 */
 //积分兑换优惠券
 function value_exchange($uid,$inte){
       $app_users = M('app_users');
       $integral = intval($app_users->where(array('user_id'=>$uid))->getField("points_value"));
      // dump($integral);
       if(!empty($integral)){
                if($integral > 100){
                    if($integral < $inte){
                         //  echo "抱歉,您的积分积分不足".$inte."无法兑换.";
                            return 0;// "抱歉,积分不足无法兑换."
                    }else{
                            $remainder = $inte % 100;
                            if($remainder){
                               // echo "抱歉,请输入100的倍数倍的积分1.";
                                //return RET_NO_V(0, "抱歉,请输入为100倍数的积分."); 
                                return false;
                            }
                        }
                    }else{
                         //return RET_NO_V(0, "抱歉您的积分不足,无法兑换.");
                      // echo "抱歉,请输入100的倍数倍的积分2.";
                        return 0;
                    }  
             }else{
                 // echo"抱歉您的积分不足,无法兑换3";
//                return RET_NO_V(0, "抱歉您的积分不足,无法兑换.");
                 return 0;
             } 
             
        $count = $inte/100;
        $coupon_info = M('coupon_info');
        $user_prize = M('user_prize');
        $user_coupon = M('user_coupon');
        $coupon_data = $coupon_info->where(array('coupon_id'=>17))->select();
        $coupon_data = $coupon_data[0];
        $result = date("Y-m-d H:i:s",time());
        $valid_end_time = strtotime($result)+(30*24*60*60); 
        //valid_end_time
        $valid_end_time = date("Y-m-d",$valid_end_time)." 23:59:59";
        $prize_data = array('prize_id'       => $coupon_data['coupon_id'],
                            'user_id'        => I('uid'),
                            'prize_angle'    => '',
                            'prize_result'   =>$coupon_data["title"],
                            'valid_end_time' =>$valid_end_time,
                            'is_used'        =>1,
                            'prize_key'      =>$coupon_data["coupon_key"],
                            'add_time'       =>$result,
                            'remark'         =>"积分兑换"
            ); 
        
           for($i=1; $i<=$count; $i++){
           //$result = integral_subtraction($uid);
           $integral -= 100;
//           dump($integral);
           $data = $app_users->where(array('user_id' => I('uid')))->save(array('points_value'=>$integral));
//           echo $app_users->getLastSql();
//           echo
//           dump($data);
           if(!$data){
               //return RET_NO_V(0, "积分兑换失败");
               return 0;
           }
           $data = $user_prize->add($prize_data);
          // dump($data);
           if(!$data)
           {
               // return RET_NO_V(0, "积分兑换失败");
               return 0;
           }
       }
       $coupon_data = array('coupon_id'     => $coupon_data['coupon_id'],
                            'user_id'       => I('uid'),
                            'coupon_type'        => 1,
                            'coupon_value'  =>3,
                            'remark'        =>"积分兑换优惠券",
                            'valid_end_time'=>$valid_end_time,
                            'from_remark'   =>'App兑换抵扣券,金额为3元',
                            'is_used'       =>1,
                            'coupon_key'    =>$coupon_data["coupon_key"],
                            'recommended_person_id'=>0,
                            'add_time'      =>   $result);
       
       for($i=1; $i<=$count; $i++){
           //dump($coupon_data);
           $data = $user_coupon->add($coupon_data);
           //echo $user_coupon->getLastSql();
          // dump($data);
           if(!$data)
           {
               return 0;
           }
       }
       return $count;
 }